﻿using System;
using System.Linq;
using SampleApp.Domain;
using SampleApp.Data;
using System.Collections.Generic;

namespace SampleApp.Service
{
    public class SysRoleService : ISysRoleService
    {
        private ISysRoleRepository sysRoleRepository;
        private ISysRoleMenuRepository sysRoleMenuRepository;
        private IRuntimeService runtimeService;
        public SysRoleService(IRuntimeService runtimeService, ISysRoleMenuRepository sysRoleMenuRepository, ISysRoleRepository sysRoleRepository)
        {
            this.runtimeService = runtimeService;
            this.sysRoleRepository = sysRoleRepository;
            this.sysRoleMenuRepository = sysRoleMenuRepository;
        }

        //public List<SysRole> GetSysRoleListByUser(string userCode)
        //{
        //    var q = this.sysRoleRepository.GetMany(i => i.RoleCode == RoleCode);
        //    return q.ToList();
        //}

        public List<SysRole> GetSysRoleList()
        {
            var q = this.sysRoleRepository.GetMany(i => true);
            return q.ToList();
        }

        public SysRole GetSysRoleByID(string roleID)
        {
            return this.sysRoleRepository.GetByID(roleID);
        }

        public void CreateSysRole(SysRole sysRole)
        {
            this.sysRoleRepository.Add(sysRole);
            this.runtimeService.UnitOfWork.Commit();
        }


        public void DeleteSysRole(string roleID)
        {
            var existsRole = this.GetSysRoleByID(roleID);
            this.sysRoleRepository.Delete(existsRole);
            this.runtimeService.UnitOfWork.Commit();
        }

        public void UpdateSysRole(SysRole sysRole)
        {
            var exists = this.GetSysRoleByID(sysRole.RoleID);
            this.sysRoleRepository.SetValues(sysRole, exists);
            this.runtimeService.UnitOfWork.Commit();
        }

        public List<string> GetMenuListByRole(string roleID)
        {
            var q = this.sysRoleMenuRepository.GetMany(i => i.RoleID == roleID).ToList();
            return q.Select(i => i.MenuID).ToList();
        }

        public void SetRoleMenu(string roleID, List<string> menuList)
        {
            var list = this.sysRoleMenuRepository.GetMany(i => i.RoleID == roleID).ToList();
            list.ForEach(i => this.sysRoleMenuRepository.Delete(i));
            var menuListAdd = menuList.Select(i => new SysRoleMenu() { RoleID = roleID, MenuID = i, RoleMenuID = Guid.NewGuid() }).ToList();
            menuListAdd.ForEach(i => this.sysRoleMenuRepository.Add(i));
            this.runtimeService.UnitOfWork.Commit();

        }




    }
}
